package nginx_handler

import (
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/route-service/constant"
	"gitee.com/zaper/route-service/model"
	"gitee.com/zaper/route-service/os_env"
	"os/exec"
	"path/filepath"
)

func StartNginx() {
	go func() {
		defer func() {
			err := recover()
			logger.Errorf("recover  %s", err)
		}()
		GetNginxConf()
		initializeNginxConf()
		cmd := fmt.Sprintf("%s%s", os_env.NginxWorkspaceValue, constant.NginxCoreScript)
		command := exec.Command("taskkill", "/f", "/im", "nginx.exe")
		command.Dir = os_env.NginxWorkspaceValue
		_, _ = command.CombinedOutput()
		var args []string
		args = append(args, "-c", fmt.Sprintf("%s%s", os_env.NginxWorkspaceValue, NginxConf))
		command = exec.Command(cmd, args...)
		command.Dir = os_env.NginxWorkspaceValue
		r, err := command.CombinedOutput()
		logger.Info("exec nginx start success! %s %s", string(r), err)
	}()
}

func initializeNginxConf() {
	port := <-model.NginxPortChan
	ip := fmt.Sprintf("%s:%s", constant.LOCALHOST, port)
	svrConf := &model.ServerConf{
		ServerName: "nginx",
		Line: []model.ServerLine{
			{Ip: ip, Weight: "10"},
		},
	}
	workSpace := filepath.Join(os_env.NginxWorkspaceValue, NginxConf)
	_ = NginxConfHandler(workSpace, svrConf)
}

func DynamicReLoadNginx() {
	cmd := fmt.Sprintf("%s%s", os_env.NginxWorkspaceValue, constant.NginxCoreScript)
	var args []string
	args = append(args, "-s", "reload", "-c", fmt.Sprintf("%s%s", os_env.NginxWorkspaceValue, NginxConf))
	command := exec.Command(cmd, args...)
	command.Dir = os_env.NginxWorkspaceValue
	_, _ = command.CombinedOutput()
	logger.Info("exec nginx reload success!")
}
